package com.sybase.dao;

/*
 Author: Leo
 Creation Date: 27-7-2012
 Creation Time: 2:32 AM
*/

import java.util.*;
import java.sql.*;

public class LowLevelDAO {
	// Data member declaration
	CallableStatement cstmt;
	ResultSet rs;
	StoredProcedureParameters spParameters;
	
	// Constructor
	protected LowLevelDAO() {
		cstmt = null;
		rs = null;
		spParameters = null;
	} // End of constructor
	
	protected ResultSet executeSimpleProcedure(Connection connection, String procedureName,
			Map<String, StoredProcedureParameters> inputParameters, Map<String, StoredProcedureParameters> outputParameters,
			int resultSetType, int concurrencyMode) throws SQLException {
		
		String dbQuery = prepareDBQuery(procedureName, inputParameters, outputParameters);
		
		// For debugging purpose
		System.out.println("[echo:dbQuery] " + dbQuery);
		
		cstmt = connection.prepareCall(dbQuery, resultSetType, concurrencyMode);
		rs = cstmt.executeQuery();
		
		return rs;
	} // End of method
	
	private String prepareDBQuery(String procedureName, Map<String, StoredProcedureParameters> inputParameters,
			Map<String, StoredProcedureParameters> outputParameters) {
		String dbQuery = "";
		String auxiliaryString = " ";
		int ceiling = 0;
		int i = 0;
		
		// Get number of elements in LinkedHashMap 
		for(Map.Entry<String, StoredProcedureParameters> entry : inputParameters.entrySet()) {
			// To suppress warning(s)
			entry.getKey();
			
			ceiling++;
		}
		
		// For debugging purpose
		System.out.println("[echo:ceiling] " + ceiling);
		
		for(Map.Entry<String, StoredProcedureParameters> entry : inputParameters.entrySet()) {
			spParameters = entry.getValue();
			
			if(++i != ceiling) {
				auxiliaryString += spParameters.getParameterName() + " = " + spParameters.getParameterValue() + ", ";
			} else {
				auxiliaryString += spParameters.getParameterName() + " = " + spParameters.getParameterValue();
			}
		}
		
		// Prepare final database query
		dbQuery += "execute " + procedureName + auxiliaryString;
		
		// For debugging purpose
		// System.out.println("[echo:query] " + query);
		
		return dbQuery;
	} // End of method
	
} // End of class